﻿package net.wangit.framework.config;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import net.wangit.util.Checker;
import net.wangit.util.StringUtil;


public class UploadConfig {

	private long maxSize;
	private Set allowedTypes;
	private Set allowedExtensions;

	public UploadConfig() {
	}

	public UploadConfig(String expression) throws Exception {
		String params[] = StringUtil.split(expression, ";");
		allowedTypes = new HashSet();
		allowedExtensions = new HashSet();
		if (Checker.isEmpty(params[0].trim()))
			maxSize = UploadSettings.getConfig().getMaxSize();
		else
			maxSize = Long.parseLong(params[0].trim());
		if (params.length > 1 && !Checker.isEmpty(params[1])) {
			String extensions[] = StringUtil.split(params[1], ",");
			for (int i = 0; i < extensions.length; i++)
				allowedExtensions.add((new StringBuilder(".")).append(
						extensions[i].trim()).toString());

		}
		if (params.length > 2 && !Checker.isEmpty(params[2])) {
			String types[] = StringUtil.split(params[2], ",");
			for (int i = 0; i < types.length; i++)
				allowedTypes.add(types[i].trim());

		}
	}

	protected void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	protected void setAllowedTypes(Set allowedTypes) {
		this.allowedTypes = allowedTypes;
	}

	protected void setAllowedExtensions(Set allowedExtensions) {
		this.allowedExtensions = allowedExtensions;
	}

	public long getMaxSize() {
		return maxSize;
	}

	public boolean isAllowedType(String contentType) {
		return allowedTypes.size() == 0 || allowedTypes.contains(contentType);
	}

	public boolean isAllowedExtension(String filename) {
		if (filename == null)
			return false;
		if (allowedExtensions.size() == 0)
			return true;
		String lowercaseFilename = filename.toLowerCase();
		for (Iterator iterator = allowedExtensions.iterator(); iterator
				.hasNext();) {
			String extension = (String) iterator.next();
			if (lowercaseFilename.endsWith(extension))
				return true;
		}

		return false;
	}
}
